package com.ruoyi.lvlian.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.io.IOException;
import java.util.Objects;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.BusinessLicenseValidator;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.lvlian.domain.*;
import com.ruoyi.lvlian.dto.BusinessLicenseInfoDto;
import com.ruoyi.lvlian.service.ICommonService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.lvlian.service.IBusinessLicenseInfoService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 主体基本信息Controller
 *
 * @author lvlian
 * @date 2024-07-24
 */
@RestController
@RequestMapping("/businessLicenseInfo")
@Api(value = "供应商 -利废商 工商信息", tags = "供应商工商信息Controller")
public class BusinessLicenseInfoController extends BaseController {
    @Autowired
    private IBusinessLicenseInfoService businessLicenseInfoService;

    @Autowired
    private ICommonService iCommonService;

    /**
     * 查询主体基本信息列表
     */
    //@RequiresPermissions("lvlian:businessLicenseInfo:list")
    @GetMapping("/list")
    public TableDataInfo list(BusinessLicenseInfoDto businessLicenseInfo) {
        if ("个人".equalsIgnoreCase(businessLicenseInfo.getSubjectType())) {
            businessLicenseInfo.setSubjectType("自然人");
        }

        if (SecurityUtils.getUserId() == 1) {
            businessLicenseInfo.setOrgCodes(new ArrayList<>(Arrays.asList("50000000")));
        } else {
            List<String> orgCodes = iCommonService.queryCurrentOrgCode(SecurityUtils.getUserId());
            if (orgCodes.isEmpty()) {
                orgCodes = businessLicenseInfo.getOrgCodes();
            }
            if (orgCodes == null || orgCodes.size() == 0) {
                return getDataTable(new ArrayList<BusinessLicenseInfo>());
            }
            if (Objects.isNull(businessLicenseInfo.getOrgCodes()) || businessLicenseInfo.getOrgCodes().isEmpty()) {
                orgCodes.removeIf(code -> code.length() != 8);
                businessLicenseInfo.setOrgCodes(orgCodes);
            }

        }


        startPage();
        List<BusinessLicenseInfo> list = businessLicenseInfoService.selectBusinessLicenseInfoList(businessLicenseInfo);
        return getDataTable(list);
    }

    @ApiOperation("查询所有账本信息")
    @GetMapping("/queryAccountList")
    public TableDataInfo queryAccountList() {
        BusinessLicenseInfoDto businessLicenseInfo = new BusinessLicenseInfoDto();
        startPage();
        businessLicenseInfo.setCreateUser(SecurityUtils.getUsername());
        List<BusinessLicenseInfoLabel> list = businessLicenseInfoService.queryAccountList(businessLicenseInfo);
        return getDataTable(list);
    }


    @ApiOperation("查询所有账本信息")
    @GetMapping("/queryAllAccountList")
    public TableDataInfo queryAllAccountList() {
        BusinessLicenseInfoDto businessLicenseInfo = new BusinessLicenseInfoDto();
        startPage();
        List<BusinessLicenseInfoLabel> list = businessLicenseInfoService.queryAllAccountList(businessLicenseInfo);
        return getDataTable(list);
    }


    /**
     * 导出主体基本信息列表
     */
/*    //@RequiresPermissions("lvlian:businessLicenseInfo:export")
    @Log(title = "主体基本信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BusinessLicenseInfo businessLicenseInfo) {
        List<BusinessLicenseInfo> list = businessLicenseInfoService.selectBusinessLicenseInfoList(businessLicenseInfo);
        ExcelUtil<BusinessLicenseInfo> util = new ExcelUtil<BusinessLicenseInfo>(BusinessLicenseInfo.class);
        util.exportExcel(response, list, "主体基本信息数据");
    }*/

    /**
     * 获取主体基本信息详细信息
     */
    //@RequiresPermissions("lvlian:businessLicenseInfo:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(businessLicenseInfoService.selectBusinessLicenseInfoById(id));
    }

    @ApiOperation("获取供应商基本信息详细信息")
    @GetMapping("/getInfoById")
    public AjaxResult getInfoById(@ApiParam(value = "供应商基本信息ID", required = true) @RequestParam(value = "id") String id) {
        return success(businessLicenseInfoService.selectBusinessLicenseInfoById(id));
    }


    @ApiOperation("根据名称查商务信息，输入完整的商务名称")
    @GetMapping("/getInfoByName")
    public AjaxResult getInfoByName(@ApiParam(value = "公司名或者自然人名称", required = true) @RequestParam(value = "name") String name) {
        return success(businessLicenseInfoService.selectBusinessLicenseInfoByName(name));
    }

    @ApiOperation("根据orgCode查询账本信息")
    @GetMapping("/selectBusinessLicenseInfoByOrgCode")
    public AjaxResult selectBusinessLicenseInfoByOrgCode(@ApiParam(value = "公司组织代码", required = true) @RequestParam(value = "orgCode") String orgCode) {
        return success(businessLicenseInfoService.selectBusinessLicenseInfoByOrgCode(orgCode));
    }


    /**
     * 新增主体基本信息
     */
/*    //@RequiresPermissions("lvlian:businessLicenseInfo:add")
    @Log(title = "主体基本信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BusinessLicenseInfo businessLicenseInfo) {
        return toAjax(businessLicenseInfoService.insertBusinessLicenseInfo(businessLicenseInfo));
    }*/
    private String validateInData(BusinessLicenseInfo po) {
        if (StringUtils.isEmpty(po.getCompanyCode())) {
            return "税号不能为空";
        }
        if (!BusinessLicenseValidator.validate(po.getCompanyCode())) {
            return "税号格式不正确";
        }


        return "success";
    }

    /**
     * 修改主体基本信息 新增主体基本信息
     */
    @ApiOperation("修改主体基本信息 新增主体基本信息")
    //@RequiresPermissions("lvlian:businessLicenseInfo:edit")
    @Log(title = "主体基本信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody @Validated BusinessLicenseInfo businessLicenseInfo) {
//        if (!"success".equalsIgnoreCase(validateInData(businessLicenseInfo))) {
//            return error(validateInData(businessLicenseInfo));
//        }
        try {
            return toAjax(businessLicenseInfoService.updateBusinessLicenseInfo(businessLicenseInfo));
        } catch (Exception e) {
            return error("保存失败");
        }
    }

    /**
     * 删除主体基本信息
     */

    @PostMapping("/remove")
    @Log(title = "删除主体基本信息", businessType = BusinessType.DELETE)
    public AjaxResult remove(@RequestBody String[] ids) {
        if (ids == null || ids.length == 0) {
            return error("未选中");
        }
        return toAjax(businessLicenseInfoService.deleteBusinessLicenseInfoByIds(ids));
    }


    @ApiOperation("导入企业及个体户")
    @PostMapping("/importInfoEnterprise")
    public AjaxResult importInfoEnterprise(MultipartFile file) {
        List<BusinessLicenseInfo> dtoList1 = null;
        List<BusinessLicenseInfo> dtoList2 = null;
        try {
            dtoList1 = businessLicenseInfoService.importInfoEnterprise(file, "利废商(企业及个体户)", 3);
            dtoList2 = businessLicenseInfoService.importInfoEnterprise(file, "供应商(企业及个体户)", 3);
        } catch (Exception e) {
            e.printStackTrace();
            return success("模板错误");
        }
        if (dtoList1 != null && dtoList2 != null) {
            dtoList1.addAll(dtoList2);
        }

        for (BusinessLicenseInfo po : dtoList1) {
            po.setSubjectType("企业");
        }

        int totalSussess = businessLicenseInfoService.bachSave(dtoList1);
        int total = dtoList1.size();
        if (Math.abs(totalSussess) > total) {
            totalSussess = total;
        }
        int totalFail = total - totalSussess;
        String msg = "解析到" + total + "条数据，" + "导入成功" + totalSussess + "条，导入失败" + totalFail + "条！";
        return success(msg);
    }


    @ApiOperation("导入供应商(自然人)")
    @PostMapping("/importInfoNaturalPerson")
    public AjaxResult importInfoNaturalPerson(MultipartFile file) {
        List<BusinessLicenseInfo> dtoList1 = null;
        List<BusinessLicenseInfo> newList = new ArrayList<>();
        try {
            dtoList1 = businessLicenseInfoService.importInfoEnterprise(file, "供应商(自然人)", 3);
            for (BusinessLicenseInfo po : dtoList1) {
                po.setSubjectType("自然人");
                newList.add(po);
            }
            int totalSussess = businessLicenseInfoService.bachSave(newList);
            int total = dtoList1.size();
            int totalFail = total - newList.size();
            String msg = "解析到" + dtoList1.size() + "条数据，" + "导入成功" + totalSussess + "条，导入失败" + Math.abs(dtoList1.size() - totalSussess) + "条！";
            return success(msg);
        } catch (Exception e) {
            e.printStackTrace();
            return success("模板错误");
        }


    }

    //
    @ApiOperation("导入本企业(企业及个体户)")
    @PostMapping("/importInfoOurCompany")
    public AjaxResult importInfoOurCompany(MultipartFile file) {
        List<BusinessLicenseInfo> dtoList1 = null;
        int totalSussess = 0;
        try {
            dtoList1 = businessLicenseInfoService.importInfoEnterprise(file, "本企业(企业及个体户)", 3);
            if (dtoList1 == null || dtoList1.isEmpty()) {
                return success("模板sheet错误");
            }
            for (BusinessLicenseInfo po : dtoList1) {
                po.setSubjectType("企业");
                po.setSubjectRole("本企业");
            }
            totalSussess = businessLicenseInfoService.bachSave(dtoList1);

        } catch (Exception e) {
            e.printStackTrace();
            return success("模板错误");
        }

        int total = dtoList1.size();
        String msg = "解析到" + total + "条数据，" + "导入成功" + Math.abs(total - totalSussess) + "条 ！";
        return success(msg);
    }
}
